﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Example.Web.Helpers
{
    public static class NavigationExtensions
    {
        public static MvcHtmlString NavigationLink(
            this HtmlHelper htmlHelper, string linkText,
            string actionName, string controllerName, object routeValues = null,
            object htmlAttributes = null,
            string wrapperElement = "li", string flag = "active")
        {
            var generatedLink = HtmlHelper.GenerateLink(
                            htmlHelper.ViewContext.RequestContext,
                            htmlHelper.RouteCollection, linkText,
                            (string)null, actionName, controllerName,
                            new RouteValueDictionary(routeValues),
                            (IDictionary<string, object>)HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));

            var wrappedElement = WrapGeneratedLink(
                            htmlHelper, actionName,
                            controllerName, wrapperElement, flag, generatedLink);

            return MvcHtmlString.Create(wrappedElement.ToString(TagRenderMode.Normal));
        }

        private static TagBuilder WrapGeneratedLink(
            HtmlHelper htmlHelper, string actionName, string controllerName,
            string wrapper, string flag, string generatedLink)
        {
            var wrapperElement = new TagBuilder(wrapper)
            {
                InnerHtml = generatedLink
            };

            if (CurrentRouteMatchesGeneratedUrl(actionName, controllerName, htmlHelper))
            {
                wrapperElement.AddCssClass(flag);
            }
            return wrapperElement;
        }

        private static bool CurrentRouteMatchesGeneratedUrl(
            string actionName, string controllerName, HtmlHelper htmlHelper)
        {
            var currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
            var currentController = (string)htmlHelper.ViewContext.RouteData.Values["controller"];

            return string.Equals(currentAction, actionName, StringComparison.CurrentCultureIgnoreCase) &&
                string.Equals(currentController, controllerName,StringComparison.CurrentCultureIgnoreCase);
        }

    }
}